<!DOCTYPE html>
<html lang="en">
<head>

    {include file="common/new_meta" /}

</head>
<body>

    {if !$company_serial}
    {include file="common/new_header" /}
    {else /}
    <div class="header-container">
        <div class="header-container-inner clearfix">
            <a href="javascript:" class="header-home-link">{:__('Vytalk')}</a>
        </div>
    </div>
    {/if}

    <div class="main-content">
        {if $company_serial && !empty($company_info)}
        <div class="page-header">
            <h2 class="page-header-heading-small">{$company_info['name']}</h2>
        </div>
        <div class="page-header">
            <h2 class="page-header-heading" style="padding: 20px 0 24px;">{:__('Join invitation')}</h2>
        </div>
        {elseif $company_serial && empty($company_info) /}
        <div class="page-header">
            <br><br><br><br>
            <h2 class="page-header-heading-small">{:__('This invitation is invalid. Please contact the sharer.')}</h2>
        </div>
        {/if}
        <div class="main-content-inner">
            {if !$company_serial}
            <div class="page-header">
                <h2 class="page-header-heading">{:__("SIGN UP, IT'S FREE")}</h2>
            </div>
            {/if}
            <div class="form-container {if $company_serial && empty($company_info)}hidden{/if}">
                <form action="" method="post" id="registerform">
                    {:token()}
                    <input type="hidden" name="cs" id="cs" value="{$company_serial}" />
                    <div class="error-return-message">Error message.</div>
                    <div class="form-group">
                        {if $Think.config.edition == 'international'}
                        <div class="country-code-select">
                            <label for="countrycode" id="PhoneCountryLabel" class="phoneCountryCode">‎+86</label>
                            <img class="downArrow" src="__CDN__/assets/img/new/dropdown_caret.svg">
                            <select class="phoneCountry" name="countrycode" id="countrycode">
                                {volist name="country_code" id="vo"}
                                <option value="{$vo['code']}" {if $vo['code'] == '+86'}selected="selected"{/if}>&nbsp;&nbsp;{$vo['country']} ( {$vo['code']} )</option>
                                {/volist}
                            </select>
                        </div>
                        {/if}
                        <input type="text" name="mobile" id="username" maxlength="128" class="form-control {if $Think.config.edition == 'international'}customize-input1{/if}" placeholder="{:__('Mobile')}" autocomplete="off" />
                        <span class="error-message"></span>
                    </div>
                    <div class="form-group" style="overflow: hidden;">
                        <input type="text" class="form-control captcha-span-input" id="img_captcha" name="img_captcha" value="" maxlength="30" placeholder="{:__('图片验证码')}" />
                        <img class="captcha-span-img" src="{:rtrim('__PUBLIC__', '/')}/index.php?s=/captcha" onclick="this.src = '{:rtrim('__PUBLIC__', '/')}/index.php?s=/captcha&r=' + Math.random();" alt="{:__('图片验证码')}" title="{:__('点击切换图片验证码')}" />
                        <span class="error-message" style="margin-top: 55px;margin-bottom: 0px;"></span>
                    </div>
                    <div class="form-group form-group-captcha">
                        <input type="text" name="captcha" id="captcha" maxlength="8" class="form-control" placeholder="{:__('短信验证码')}" autocomplete="off" />
                        <span class="error-message"></span>
                        <a class="btn-get-captcha" href="javascript:;">{:__('获取短信验证码')}</a>
                    </div>
                    <div class="form-group">
                        <input type="password" name="password" id="password" maxlength="30" class="form-control" placeholder="{:__('Password')}" autocomplete="off" />
                        <span class="error-message"></span>
                    </div>
                    <div class="form-group">
                        <input type="text" name="nickname" id="nickname" maxlength="30" class="form-control" placeholder="{:__('Nickname')}" autocomplete="off" />
                        <span class="error-message"></span>
                    </div>
                    <input type="hidden" id="source" name="source" value="0" />
                    {if $company_serial && !empty($company_info)}
                    <button class="btn-primary" type="submit">{:__('Join')}</button>
                    {else /}
                    <button class="btn-primary" type="submit">{:__('Sign up')}</button>
                    {/if}
                    {if !$company_serial}
                    <p class="agree">
                        {:__('By signing up, I agree to the ')}<a target="_blank" href="/admin/index/about?t=privacy" class="link-primary">{:__('Privacy Policy')}</a>{:__('and')}<a target="_blank" href="/admin/index/about?t=terms" class="link-primary">{:__('Terms of Service')}</a>{:__('.')}
                    </p>
                    <div class="form-check clearfix"></div>
                    <div class="form-group reg-section">
                        <hr class="hr">
                        <p class="extra">
                            {:__('Already have an account?')}<a href="/admin/index/login" class="reg-link">{:__('Sign in lower')}</a>
                        </p>
                    </div>
                    {/if}
                </form>
            </div>
        </div>
    </div>

    {if !$company_serial}
    {include file="common/new_footer" /}
    {/if}

    <script>
    // 选中国际区号
    $("#countrycode").change(function(){
        $("#PhoneCountryLabel").text($(this).val());
    })

    /* 发送验证码逻辑 - start */
    // btn-get-captcha
    var canSendCaptcha = true;
    $('.btn-get-captcha').click(function(e) {
        if (canSendCaptcha && validateUsername() && validateImgCaptcha()) {
            errorReturn("");

            var mobile = $('#username').val();
            var img_captcha = $('#img_captcha').val();
            var cs = $('#cs').val();
            // 请求后台获取数据:请求api统一接口
            $.post('{:url(\'api/Sms/send\')}',{mobile:mobile,captcha:img_captcha,cs:cs},function(data){
                console.log(data);
                if (data.data.type == 'img_captcha') {
                    $("#img_captcha").val("");
                    $(".captcha-span-img").attr("src", "{:rtrim('__PUBLIC__', '/')}/index.php?s=/captcha&r=" + Math.random());
                }

                if(data.code==true || data.code==1){
                    layer.msg(data.msg);
                    // 发送验证码成功后，倒计时
                    showCountdown();
                }else{
                    if (cs == "") {
                        errorReturn(data.msg);
                    }else {
                        if (data.data != null) {
                            if (data.data.go_login == 1) {
                                errorReturn(data.msg + '，<a href="/admin/index/login" target="_blank" style="text-decoration: underline;color: #227bff;">{:__("Direct Login")}</a>');
                            }else{
                                errorReturn(data.msg);
                            }
                        }else{
                            errorReturn(data.msg);
                        }
                    }
                }
            },'json');
        }
    });

    function showCountdown() {
        canSendCaptcha = false;
        var time = 60;
        var $btn = $('.btn-get-captcha');
        $btn.addClass('disabled').text("{:__('Sent')}(" + time-- + ")");
        var timerId = setInterval(function() {
            if (time < 1) {
                clearInterval(timerId)
                $btn.removeClass('disabled').text("{:__('Resend')}");
                canSendCaptcha = true;
                return
            }
            $btn.text("{:__('Sent')}(" + time-- + ")");
        }, 1000);
    }
    /* 发送验证码逻辑 - end */

    /* 表单校验 - start */
    var nicknameTouched = false,
        usernameTouched = false,
        passwordTouched = false,
        captchaTouched = false,
        imgCaptchaTouched = false;

    $('#username').focus(function(e) {
        if ($(this).parent('.form-group').hasClass('has-error')) {
            clearError('username');
        }

        usernameTouched = true;
    })
    $('#username').blur(function(e) {
        if (usernameTouched) {
            validateUsername();
        }
    });

    $('#img_captcha').focus(function(e) {
        if ($(this).parent('.form-group').hasClass('has-error')) {
            clearError('img_captcha');
        }

        imgCaptchaTouched = true;
    })
    $('#img_captcha').blur(function(e) {
        if (imgCaptchaTouched) {
            validateImgCaptcha();
        }
    });

    $('#captcha').focus(function(e) {
        if ($(this).parent('.form-group').hasClass('has-error')) {
            clearError('captcha');
        }

        captchaTouched = true;
    })
    $('#captcha').blur(function(e) {
        if (captchaTouched) {
            validateCaptcha();
        }
    });

    $('#password').focus(function(e) {
        if ($(this).parent('.form-group').hasClass('has-error')) {
            clearError('password');
        }

        passwordTouched = true;
    })
    $('#password').blur(function(e) {
        if (passwordTouched) {
            validatePassword();
        }
    });

    $('#nickname').focus(function(e) {
        if ($(this).parent('.form-group').hasClass('has-error')) {
            clearError('nickname');
        }

        nicknameTouched = true;
    })
    $('#nickname').blur(function(e) {
        if (nicknameTouched) {
            validateNickname();
        }
    });

    $('#registerform').on('submit', function(e) {
        e.preventDefault();

        if (validateUsername() && validateCaptcha() && validatePassword() && validateNickname()) {
            $(".btn-primary").attr("disabled", "disabled");

            var index = layer.load(0, {
                shade: false
            }); //0代表加载的风格，支持0-2

            errorReturn("");

            $.ajax({
                url:'/admin/index/register',
                data:$('form').serialize(),
                type:'post',
                success:function(data){
                    layer.close(index);

                    $(".btn-primary").removeAttr("disabled");

                    if (data['data'] != "") {
                        $("input[name=__token__]").val(data['data']['token']);
                    }

                    if (data['code']==1) {
                        if ($("#cs").val() != "") {
                            layer.msg(data['msg']);

                            setTimeout(function(){
                                if (data['url'] == "") {
                                    window.location.href="/admin/index/login";
                                }else{
                                    window.location.href=data['url'];
                                }
                            },2500);
                        }else{
                            window.location.href=data['url'];
                        }
                    }else{
                        errorReturn(data['msg']);
                    }
                }
            });

            return false;
        }

        return false;
    });

    function validateNickname() {
        clearError('nickname');

        var nickname = $('#nickname').val();
        var errorMessage = '';

        if (nickname.trim() === '') {
            errorMessage = "{:__('Please enter your nickname')}";
        } else if (nickname.length > 20) {
            errorMessage = "{:__('Nickname must be within 20 characters')}";
        }

        if (errorMessage) {
            showError('nickname', errorMessage);
            return false;
        } else {
            return true;
        }
    }

    function validateUsername() {
        clearError('username');

        var username = $('#username').val();
        var errorMessage = '';
        var rMobile = /^1[3-9]\d{9}$/;

        if (username.trim() === '') {
            errorMessage = "{:__('Please enter your mobile')}";
        } else if (!rMobile.test(username)) {
            errorMessage = "{:__('Please enter a valid mobile')}";
        }

        if (errorMessage) {
            showError('username', errorMessage);
            return false;
        } else {
            return true;
        }
    }

    function validatePassword() {
        clearError('password');

        var password = $('#password').val();
        var errorMessage = '';
        if (password === '') {
            errorMessage = "{:__('Please enter your Password')}";
        }

        if (errorMessage) {
            showError('password', errorMessage);
            return false;
        } else {
            return true;
        }
    }

    function validateImgCaptcha() {
        clearError('img_captcha', 'captcha');

        var img_captcha = $('#img_captcha').val();
        var errorMessage = '';
        if (img_captcha === '') {
            errorMessage = "{:__('请输入图片验证码')}";
        }

        if (errorMessage) {
            showError('img_captcha', errorMessage, 'captcha');
            return false;
        } else {
            return true;
        }
    }

    function validateCaptcha() {
        clearError('captcha');

        var captcha = $('#captcha').val();
        var errorMessage = '';
        if (captcha === '') {
            errorMessage = "{:__('请输入短信验证码')}";
        }

        if (errorMessage) {
            showError('captcha', errorMessage);
            return false;
        } else {
            return true;
        }
    }

    function showError(inputIdName, errorMessage, type) {
        var inputElement = $('#' + inputIdName);
        if (inputElement.length) {
            if (type != 'captcha') {
                inputElement.next('.error-message').text(errorMessage);
            }else{
                inputElement.next().next('.error-message').text(errorMessage);
            }
            inputElement.parent('.form-group').addClass('has-error');
        }
    }

    function clearError(inputIdName, type) {
        var inputElement = $('#' + inputIdName);
        if (inputElement.length) {
            if (type != 'captcha') {
                inputElement.next('.error-message').empty();
            }else{
                inputElement.next().next('.error-message').empty();
            }
            inputElement.parent('.form-group').removeClass('has-error');
        }
    }

    /* 表单校验 - end */

    function errorReturn(msg) {
        if (msg == '') {
            $(".error-return-message").html("");
            $(".error-return-message").hide();
        }else{
            $(".error-return-message").html(msg);
            $(".error-return-message").show();
        }
    }
    </script>
</body>
</html>